<?php

namespace app\admin\controller;
use app\common\model\Config as ConfigModel;
use app\common\controller\Backend;
use think\Db;
use think\Session;

/**
 * 酒店管理
 *
 * @icon   fa fa-list
 * @remark 用于统一管理网站的所有分类,分类可进行无限级分类,分类类型请在常规管理->系统配置->字典配置中添加
 */
class Activity extends Backend
{

    protected $hid = null;
    protected $adminId = null;
    protected $mainhost = "";


    public function _initialize()
    {
        parent::_initialize();
        $this->mainhost = "http://".$_SERVER["HTTP_HOST"];
     /*   $this->hid = Session::get("admin")["hotelid"];
        $this->adminId = Session::get("admin")["id"];*/

        //未结束的
        $nowdate = date("Y-m-d");
        $list = db("activity")->field("id,title")->where("enddate >= '$nowdate'")->where(['status'=>'normal'])->select();
        $this->assign("hlist",$list);

        $city = db("city")->where(['parentId'=>-1])->select();
        $citylist = db("city")->where("parentId != '-1'")->select();
        $this->assign("city",$city);
        $this->assign("citylist",$citylist);

    }

    /**
     * 查看
     */
    public function index()
    {

        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {

            $search = $this->request->request("search");
            $search = trim($search);
            $model = model('Activity');

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();


            if($this->adminId == 1){
                $total = $model->where('title','like','%'.$search.'%')->order($sort, $order)->count();
                $list = $model
                    ->where('title','like','%'.$search.'%')
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            }else{
                $total = $model->where('title','like','%'.$search.'%')->order($sort, $order)->count();
                $list = $model
                    ->where('title','like','%'.$search.'%')
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            }




            $result = array("total" => $total, "rows" => $list);

            return json($result);


        }
        return $this->view->fetch();
    }

    /**
     * 批量更新
     */
    public function multi($ids = "")
    {

        $ids = $ids ? $ids : $this->request->param("ids");
        if ($ids) {
            $model = model('Activity');
            if ($this->request->has('params')) {
                parse_str($this->request->post("params"), $values);
                $values = $this->auth->isSuperAdmin() ? $values : array_intersect_key($values, array_flip(is_array($this->multiFields) ? $this->multiFields : explode(',', $this->multiFields)));
                if ($values) {

                    $count = 0;
                    Db::startTrans();
                    try {
                        $list = $model->where("id", 'in', $ids)->select();
                        foreach ($list as $index => $item) {
                            $count += $item->isUpdate(true)->save($values);
                        }
                        Db::commit();
                    } catch (PDOException $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                    } catch (Exception $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                    }
                    if ($count) {
                        $this->success();
                    } else {
                        $this->error(__('No rows were updated'));
                    }
                } else {
                    $this->error(__('You have no permission'));
                }
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }


    /**
     * 删除
     */
    public function del($ids = "")
    {


        if ($ids) {
            $model = model('Activity');
            $list = $model->where("id", 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    //curl请求
    public function httpRequest($url, $data='', $method='GET'){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
        if($method=='POST'){
            curl_setopt($curl, CURLOPT_POST, 1);
            if ($data != ''){
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            }
        }
        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($curl);
        curl_close($curl);
        return $result;
    }

    //生成带有参数的二维码
    public function pathImg($aid){
        $activity_id = $aid; //活动id
        //配置APPID、APPSECRET
        $APPID = "wxd3ed1291e43598cd";
        $APPSECRET =  "3c112f9dced28d11507ea034efa3d099";
        //获取access_token
        $access_token = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$APPID&secret=$APPSECRET";
        $json = $this->httpRequest($access_token);
        $json = json_decode($json,true);
        $ACCESS_TOKEN = $json['access_token'];
        //如果要获取小程序码，请求这个接口
        $qcode ="https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=$ACCESS_TOKEN";
        $param = json_encode(array("page"=>"activity/pages/activity/activity","width"=>"280","scene"=>$activity_id));
        //$param = json_encode(array("page"=>"pages/hoteldetail/detail","width"=>"280","scene"=>$activity_id));
        //如果要获取二维码，请求这个接口
        // $qcode ="https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=$ACCESS_TOKEN";
        // $param = json_encode(array("path"=>"pages/comm_details/comm_details?goods_id=19","width"=> 150));
        //POST参数
        $result = $this->httpRequest($qcode, $param, "POST");


        //生成二维码

        $tm = time();

        $path = ROOT_PATH."public/uploads/share/";
        $fxname = $path."activity_".$activity_id."_".$tm.".png";
        $fxurl = "/uploads/share/"."activity_".$activity_id."_".$tm.".png";
        file_put_contents($fxname, $result);

        return $fxurl;

        //qrcode.png这个就是你生成的二维码图片,可以存到你指定的路径,例如:/update/img/qrcode.png
      //  $base64_image ="data:image/png;base64,".base64_encode($result);
       // echo $base64_image;
    }


    /**
     * 添加
     */
    public function add()
    {

        if ($this->request->isPost()) {
            $model = model('Activity');
            $params = $this->request->post();

            if ($params) {
                $params = $this->preExcludeFields($params);
                if($params['row']['reactids']){
                    $reactids = implode(",",$params['row']['reactids']);
                }else{
                    $reactids = "";
                }
                if($params['label']){
                    $label = implode(",",$params['label']);
                }else{
                    $label = "";
                }

                $params['row']['label'] = $label;
                $params['row']['reactids'] = $reactids;

                if(!empty($params["row"]["imgs"])){
                    $imgs = explode(",",$params["row"]["imgs"]);
                    $params["row"]["img"] = $imgs[0];
                }else{
                    $params["row"]["img"] = "";
                }

                $params['row']['createtime'] =time();



                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }

                //替换富文本图片未绝对路径
                if($params['row']['contentimg']){
                    $fwbcontent =$params['row']['contentimg'];
                    $fwbcontent2 = pregReplaceImg2($fwbcontent,$this->mainhost);
                    $params['row']['contentimg'] = $fwbcontent2;//带有绝对路径
                }

                $result = false;
                Db::startTrans();

                try {

                    $result = $model->insertGetId($params['row']);
                    $up["updatetime"] = time();
                    //生成分享二维码
                    $fxurl = $this->pathImg($result);
                    $up["fx_ewm"] = $fxurl;
/*
                    //生成弧度图片
                    $imgpath = ROOT_PATH.'/public'.$params["row"]["img"];
                    //生成图片路径
                    $posterimg = "poster_".$result."_".time().".jpg";
                    $imgpath2 = ROOT_PATH.'/public/uploads/poster/'.$posterimg;
                    $imgpath2_2 = '/uploads/poster/'.$posterimg;//保存到数据库的路径
                    $up["fx_actimg"] = $imgpath2_2;
                    $imgg = radius_img($imgpath);
                    imagepng($imgg,$imgpath2);
                    imagedestroy($imgg);

                    //绘制海报 完整的海报 分2个步骤，后只绘制不带有用户信息的海报，前台用户点击生成海报时 再将头像和姓名在第一个步的基础上生成 返回完整海报地址
                    //绘制第一步海报，如果用户信息事先能确定，怎只要一步即可。

                    $posterimg2 = "poster_".$result."_1_".time().".jpg";
                    $filename = ROOT_PATH.'/public/uploads/poster/'.$posterimg2;
                    //这里要判断标题的长度 前端最多显示2行

                    $alltext = $params["row"]["title"];
                    $textlen =  mb_strlen($alltext, 'utf8');
                    $text1 = subText($alltext,24);
                    if($textlen > 24){
                        $text2 = subText4($alltext,24);
                    }else{
                        $text2 = "";
                    }

                    $bgimg = ROOT_PATH.'/public/poster/posterbg.jpg';//底图
                    $bgactimg = $imgpath2;
                    $ermurl = ROOT_PATH.'/public'.$fxurl;
                    $fonttff = ROOT_PATH.'/public/poster/simhei.ttf';
                    $remark = "★我发现这个东西还不错呢";
                    $config = array(
                        'text'=>array(
                            array(
                                'text'=>$remark,
                                'left'=>140,
                                'top'=>160,
                                'fontPath'=>$fonttff,    //字体文件
                                'fontSize'=>24,             //字号
                                'fontColor'=>'71,61,2',       //字体颜色
                                'angle'=>0,
                            ),
                            array(
                                'text'=>$text1,
                                'left'=>50,
                                'top'=>-330,
                                'fontPath'=>$fonttff,    //字体文件
                                'fontSize'=>24,             //字号
                                'fontColor'=>'83,83,83',       //字体颜色
                                'angle'=>0,
                            ),
                            array(
                                'text'=>$text2,
                                'left'=>50,
                                'top'=>-280,
                                'fontPath'=>$fonttff,    //字体文件
                                'fontSize'=>24,             //字号
                                'fontColor'=>'83,83,83',       //字体颜色
                                'angle'=>0,
                            )
                        ),
                        'image'=>array(
                            array(
                                'url'=>$bgactimg, //活动图片
                                'left'=>49,
                                'top'=>240,
                                'right'=>0,
                                'stream'=>0,
                                'bottom'=>0,
                                'width'=>651,
                                'height'=>700,
                                'opacity'=>100,
                            ),
                            array(
                                'url'=>$ermurl, //图片资源路径 二维码
                                'left'=>520,
                                'top'=>-55,
                                'stream'=>0,             //图片资源是否是字符串图像流
                                'right'=>0,
                                'bottom'=>0,
                                'width'=>180,
                                'height'=>180,
                                'opacity'=>100
                            ),
                        ),
                        'background'=>$bgimg,
                    );
                    createPoster($config,$filename);

                    //绘制海报上面的价格 绘制多边形
                    $background = $filename;
                    $posterimgone = "poster_".$result."_one_".time().".jpg";
                    $filenameone = ROOT_PATH.'/public/uploads/poster/'.$posterimgone;

                    $price =  $alltext = $params["row"]["price"];
                    $preprice =  '原价  '.$alltext = $params["row"]["preprice"];
                    generateImg ( $background,$filenameone,$fonttff,$price,$preprice);




                    //绘制人民币符号 因为直接用符号会乱码 不识别 这里改成 图片
                    $bgimg2 = $filenameone;//底图
                    $bgimgrmb = ROOT_PATH.'/public/poster/rmb.png';//底图
                    $rmbconfig = array(
                        'image'=>array(
                            array(
                                'url'=>$bgimgrmb, //头像
                                'left'=>153,
                                'top'=>-420,
                                'right'=>0,
                                'stream'=>0,
                                'bottom'=>0,
                                'width'=>24,
                                'height'=>29,
                                'opacity'=>100,
                            ),
                            array(
                                'url'=>$bgimgrmb, //头像
                                'left'=>575,
                                'top'=>-420,
                                'right'=>0,
                                'stream'=>0,
                                'bottom'=>0,
                                'width'=>34,
                                'height'=>38,
                                'opacity'=>100,
                            )
                        ),
                        'background'=>$bgimg2,
                    );

                    $posterimgtwo = "poster_".$result."_two_".time().".jpg";
                    $filenametwo = ROOT_PATH.'/public/uploads/poster/'.$posterimgtwo;
                    $filenametwo2 = '/uploads/poster/'.$posterimgtwo;
                    createPoster($rmbconfig,$filenametwo);

                    $up["fx_posterone"] = $filenametwo2;*/


                    $eid = db("activity")->where(['id'=>$result])->update($up);
                    Db::commit();


                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }
    /**
     * 编辑
     */
    public function edit($ids = null)
    {


        //未结束的
        $nowdate = date("Y-m-d");
        $list = db("activity")->field("id,title")->where("id != $ids")->where("enddate >= '$nowdate'")->where(['status'=>'normal'])->select();
        $this->assign("hlist2",$list);

        $model = model('Activity');
        $row = $model->get($ids)->toArray();

        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($this->request->isPost()) {
            $params = $this->request->post();
            if ($params) {
                $params = $this->preExcludeFields($params);

                try {

                    if($params['row']['reactids']){
                        $reactids = implode(",",$params['row']['reactids']);
                    }else{
                        $reactids = "";
                    }

                    if($params['label']){
                        $label = implode(",",$params['label']);
                    }else{
                        $label = "";
                    }

                    $params['row']['label'] = $label;
                    $params['row']['reactids'] = $reactids;

                    if(!empty($params["row"]["imgs"])){
                        $imgs = explode(",",$params["row"]["imgs"]);
                        $params["row"]["img"] = $imgs[0];
                    }else{
                        $params["row"]["img"] = "";
                    }


                    if($params['row']['contentimg']){
                        $fwbcontent =$params['row']['contentimg'];
                        $fwbcontent2 = pregReplaceImg2($fwbcontent,$this->mainhost);
                        $params['row']['contentimg'] = $fwbcontent2;//带有绝对路径
                    }




                    if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                        $params[$this->dataLimitField] = $this->auth->id;
                    }

                    $result = $model->where("id=$ids")->update($params["row"]);

/*                    //编辑时修改海报名称
                    //二维码不用重新生成
                    $fxurl = ROOT_PATH."/public".$row['fx_ewm'];
                    //生成弧度图片
                    $imgpath = ROOT_PATH.'/public'.$params["row"]["img"];
                    //生成图片路径
                    $posterimg = "poster_".$ids."_".time().".jpg";
                    $imgpath2 = ROOT_PATH.'/public/uploads/poster/'.$posterimg;
                    $imgpath2_2 = '/uploads/poster/'.$posterimg;//保存到数据库的路径
                    $up["fx_actimg"] = $imgpath2_2;
                    $imgg = radius_img($imgpath);
                    imagepng($imgg,$imgpath2);
                    imagedestroy($imgg);


                    //绘制海报 完整的海报 分2个步骤，后只绘制不带有用户信息的海报，前台用户点击生成海报时 再将头像和姓名在第一个步的基础上生成 返回完整海报地址
                    //绘制第一步海报，如果用户信息事先能确定，怎只要一步即可。
                    $posterimg2 = "poster_".$ids."_1_".time().".jpg";
                    $filename = ROOT_PATH.'/public/uploads/poster/'.$posterimg2;
                    //这里要判断标题的长度 前端最多显示2行
                    $alltext = $params["row"]["title"];
                    $textlen =  mb_strlen($alltext, 'utf8');
                    $text1 = subText($alltext,24);
                    if($textlen > 24){
                        $text2 = subText4($alltext,24);
                    }else{
                        $text2 = "";
                    }

                    $bgimg = ROOT_PATH.'/public/poster/posterbg.jpg';//底图
                    $bgactimg = $imgpath2;
                    $ermurl = $fxurl;
                    $fonttff = ROOT_PATH.'/public/poster/simhei.ttf';
                    $remark = "★我发现这个东西还不错呢";
                    $config = array(
                        'text'=>array(
                            array(
                                'text'=>$remark,
                                'left'=>140,
                                'top'=>160,
                                'fontPath'=>$fonttff,    //字体文件
                                'fontSize'=>24,             //字号
                                'fontColor'=>'71,61,2',       //字体颜色
                                'angle'=>0,
                            ),
                            array(
                                'text'=>$text1,
                                'left'=>50,
                                'top'=>-330,
                                'fontPath'=>$fonttff,    //字体文件
                                'fontSize'=>24,             //字号
                                'fontColor'=>'83,83,83',       //字体颜色
                                'angle'=>0,
                            ),
                            array(
                                'text'=>$text2,
                                'left'=>50,
                                'top'=>-280,
                                'fontPath'=>$fonttff,    //字体文件
                                'fontSize'=>24,             //字号
                                'fontColor'=>'83,83,83',       //字体颜色
                                'angle'=>0,
                            )
                        ),
                        'image'=>array(
                            array(
                                'url'=>$bgactimg, //活动图片
                                'left'=>49,
                                'top'=>240,
                                'right'=>0,
                                'stream'=>0,
                                'bottom'=>0,
                                'width'=>651,
                                'height'=>700,
                                'opacity'=>100,
                            ),
                            array(
                                'url'=>$ermurl, //图片资源路径 二维码
                                'left'=>520,
                                'top'=>-55,
                                'stream'=>0,             //图片资源是否是字符串图像流
                                'right'=>0,
                                'bottom'=>0,
                                'width'=>180,
                                'height'=>180,
                                'opacity'=>100
                            ),
                        ),
                        'background'=>$bgimg,
                    );

                    createPoster($config,$filename);


                    //绘制海报上面的价格 绘制多边形
                    $background = $filename;
                    $posterimgone = "poster_".$ids."_one_".time().".jpg";
                    $filenameone = ROOT_PATH.'/public/uploads/poster/'.$posterimgone;
                    $price =  $alltext = $params["row"]["price"];
                    $preprice =  '原价  '.$alltext = $params["row"]["preprice"];
                    generateImg ( $background,$filenameone,$fonttff,$price,$preprice);
                    //绘制人民币符号 因为直接用符号会乱码 不识别 这里改成 图片
                    $bgimg2 = $filenameone;//底图
                    $bgimgrmb = ROOT_PATH.'/public/poster/rmb.png';//底图
                    $rmbconfig = array(
                        'image'=>array(
                            array(
                                'url'=>$bgimgrmb, //人民币
                                'left'=>153,
                                'top'=>-420,
                                'right'=>0,
                                'stream'=>0,
                                'bottom'=>0,
                                'width'=>24,
                                'height'=>29,
                                'opacity'=>100,
                            ),
                            array(
                                'url'=>$bgimgrmb, //人民币
                                'left'=>575,
                                'top'=>-420,
                                'right'=>0,
                                'stream'=>0,
                                'bottom'=>0,
                                'width'=>34,
                                'height'=>38,
                                'opacity'=>100,
                            )
                        ),
                        'background'=>$bgimg2,
                    );

                    $posterimgtwo = "poster_".$ids."_two_".time().".jpg";
                    $filenametwo = ROOT_PATH.'/public/uploads/poster/'.$posterimgtwo;
                    $filenametwo2 = '/uploads/poster/'.$posterimgtwo;
                    createPoster($rmbconfig,$filenametwo);

                    $up["fx_posterone"] = $filenametwo2;

                    $eid = db("activity")->where(['id'=>$ids])->update($up);*/


                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }


        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    /**
     * Selectpage搜索
     *
     * @internal
     */
    public function selectpage()
    {
        return parent::selectpage();
    }
}
